/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import BLO.ProjectBLO;
import BLO.TaskBLO;
import BLO.UserBLO;
import DTO.Date;
import DTO.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.SupportUtil;

/**
 *
 * @author ThanhTai
 */
public class Controller extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
        SupportUtil support = new SupportUtil();
        HttpSession session = request.getSession();
        try {
            if (action.equals("Login")) {
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                // call funcation checkLogin
                //taint
                session.removeAttribute("PROJECTNAME");
                session.removeAttribute("MINESTONENAME");
                session.removeAttribute("PROJECTID");
                session.removeAttribute("MINESTONEID");

                String pathLogin = getServletContext().getRealPath("/") + "xml/Users.xml";
                User check = support.checkLogin(pathLogin, username, password);
                // if login valid
                if (check != null && !check.getUsername().equals("")) {
                    session.setAttribute("ROLE", check.getUserRole());
                    session.setAttribute("USERNAME", check.getUsername());
                    session.setAttribute("FULLNAME", check.getFullName());
                    session.setAttribute("Path", getServletContext().getRealPath("/"));
                    String userRole = check.getUserRole();
                    // if user role is staff
                    if (userRole.equals("pm")) {
                        ProjectBLO blo = new ProjectBLO();

                        String pathProjects = getServletContext().getRealPath("/") + "xml/Projects.xml";
                        blo.getAllProjectOfProjectManager(pathProjects, check.getUsername().trim());

                        RequestDispatcher rd = request.getRequestDispatcher("pmMainPage.jsp");
                        rd.forward(request, response);
                    } else if (userRole.equals("admin")) {
                        RequestDispatcher rd = request.getRequestDispatcher("adminMainPage.jsp");
                        rd.forward(request, response);
                    } else if (userRole.equals("staff")) {
                        TaskBLO taskBLO = new TaskBLO();
                        String pathTasks = getServletContext().getRealPath("/") + "xml/Task.xml";
                        taskBLO.getTasksByUser(pathTasks, check.getUsername().trim());

                        RequestDispatcher rd = request.getRequestDispatcher("staffMainPage.jsp");
                        rd.forward(request, response);
                    }
                } else {
                    // if login invalid tranfers a flag to jsp
                    request.setAttribute("FLAG", "invalid");
                    RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
                    rd.forward(request, response);
                }
            } else if (action.equals("GetMinestones")) {
                try {
                    String projectIDstring = request.getParameter("ProjectID");
                    String projectName = request.getParameter("ProjectName");
                    int projectID = Integer.parseInt(projectIDstring);
                    ProjectBLO blo = new ProjectBLO();
                    String filePath = getServletContext().getRealPath("/") + "xml/Minestones.xml";
                    blo.getAllMinestonsOfProjectID(filePath, projectID);

                    session.setAttribute("PROJECTNAME", projectName);
                    session.setAttribute("PROJECTID", projectID);
                    session.removeAttribute("MINESTONENAME");
                    session.removeAttribute("MINESTONEID");
                    RequestDispatcher rd = request.getRequestDispatcher("pmMainPage.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("GetTasks")) {
                try {
                    String minestoneIDstring = request.getParameter("MinestoneID");
                    String minestoneName = request.getParameter("MinestoneName");
                    int minestoneID = Integer.parseInt(minestoneIDstring);
                    ProjectBLO blo = new ProjectBLO();
                    String filePath = getServletContext().getRealPath("/") + "xml/Tasks.xml";
                    blo.getAllTasksOfMinestoneID(filePath, minestoneID);

                    session.setAttribute("MINESTONENAME", minestoneName);
                    session.setAttribute("MINESTONEID", minestoneID);
                    RequestDispatcher rd = request.getRequestDispatcher("pmMainPage.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("logout")) {
                try {
                    session.removeAttribute("PROJECTNAME");
                    session.removeAttribute("MINESTONENAME");
                    session.removeAttribute("PROJECTID");
                    session.removeAttribute("MINESTONEID");
                    RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("SearchTask")) {
                try {
                    String txtTaskNameSearch = request.getParameter("txtTaskNameSearch");
                    String SDyearSearch = request.getParameter("SDyearSearch");
                    String SDmonthSearch = request.getParameter("SDmonthSearch");
                    String SDdaySearch = request.getParameter("SDdaySearch");
                    String EDyearSearch = request.getParameter("EDyearSearch");
                    String EDmonthSearch = request.getParameter("EDmonthSearch");
                    String EDdaySearch = request.getParameter("EDdaySearch");
                    String statusSearch = request.getParameter("statusSearch");
                    Integer minestoneId = (Integer) session.getAttribute("MINESTONEID");
                    Date startDay = new Date(Integer.parseInt(SDyearSearch), Integer.parseInt(SDmonthSearch), Integer.parseInt(SDdaySearch));
                    Date endDay = new Date(Integer.parseInt(EDyearSearch), Integer.parseInt(EDmonthSearch), Integer.parseInt(EDdaySearch));
                    TaskBLO blo = new TaskBLO();

                    String filePath = getServletContext().getRealPath("/") + "xml/Tasks.xml";
                    blo.getTasksBySearch(filePath, minestoneId, txtTaskNameSearch, startDay, endDay, statusSearch);

                    RequestDispatcher rd = request.getRequestDispatcher("pmMainPage.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("MainPage")) {
                try {
                    session.removeAttribute("PROJECTNAME");
                    session.removeAttribute("MINESTONENAME");
                    session.removeAttribute("PROJECTID");
                    session.removeAttribute("MINESTONEID");
                    RequestDispatcher rd = request.getRequestDispatcher("pmMainPage.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("Assign Task to staff")) {
                try {
                    session.removeAttribute("PROJECTNAME");
                    session.removeAttribute("MINESTONENAME");
                    session.removeAttribute("PROJECTID");
                    session.removeAttribute("MINESTONEID");
                    RequestDispatcher rd = request.getRequestDispatcher("pmAssignTask.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("Add Members of Project")) {
                try {
                    session.removeAttribute("PROJECTNAME");
                    session.removeAttribute("MINESTONENAME");
                    session.removeAttribute("PROJECTID");
                    session.removeAttribute("MINESTONEID");
                    RequestDispatcher rd = request.getRequestDispatcher("pmAddMembersOfProject.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("getProjectForAddMembers")) {
                try {
                    String projectID = request.getParameter("ProjectID");
                    String projectName = request.getParameter("ProjectName");
                    request.setAttribute("ProjectID", projectID);
                    request.setAttribute("ProjectName", projectName);
                    UserBLO blo = new UserBLO();
                    String filePath = getServletContext().getRealPath("/") + "xml/Users.xml";
                    blo.getAllUserNotInProject(filePath, Integer.parseInt(projectID));
                    RequestDispatcher rd = request.getRequestDispatcher("pmAddMembersOfProject.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (action.equals("ACTION_EXPORT_PDF")) {
                // active when click on button Export
                String projectName = (String) session.getAttribute("PROJECTNAME");
                String minestoneName = (String) session.getAttribute("MINESTONENAME");
                // create path for xml, xsl, fo, and pdf
                String xmlPath = getServletContext().getRealPath("/") + "xml/Tasks.xml";
                String xslPath = getServletContext().getRealPath("/") + "xsl/TasksFO.xsl";
                String foPath = getServletContext().getRealPath("/") + "fo/TasksFO.fo";
                String pdfPath = getServletContext().getRealPath("/") + "pdf/"
                        + projectName + "Tasks.pdf";

                // create a params list to pass to xsl file
                List<Map<String, String>> params = new ArrayList<Map<String, String>>();
                Map<String, String> paramMap = new HashMap<String, String>();
                paramMap.put("NAME", "projectName");
                paramMap.put("VALUE", projectName);
                params.add(paramMap);
                paramMap = new HashMap<String, String>();
                paramMap.put("NAME", "minestoneName");
                paramMap.put("VALUE", minestoneName);
                params.add(paramMap);

                // call function to transform xml, xsl to a *.fo file
                support.transform(xmlPath, xslPath, foPath, params);
                // call function to transform *.fo file to pdf fil
                support.exportPDF(foPath, pdfPath);
                // dispatch back to main page
                RequestDispatcher rd = request.getRequestDispatcher("pmMainPage.jsp");
                rd.forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
